package com.android.lovely.ui.chat

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.graphics.toColorInt
import com.android.lovely.R
import com.android.lovely.databinding.LayoutChatStyleBinding
import com.android.lovely.databinding.LayoutSplashLoginBinding
import com.kotlin.extensions.inflater.LayoutInflaterExt.layoutInflater
import com.kotlin.extensions.view.ViewExt.clickable
import com.liupei.shape.widget.ShapeTextView

/**
 *
 * @author why
 * @date 2025/3/31 01:52
 */
class ChatStyleWidget @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    val list = arrayListOf(
        "#7C7C7E", "#D2D2D2", "#FFFFFF", "#A3A7D3", "#939CFF", "#21265D", "#121214"
    )
    private var currentSelect = 0

    private val mBinding by lazy {
        LayoutChatStyleBinding.inflate(layoutInflater, this, false)
    }

    var listener: OnStyleClickListener? = null

    init {
        addView(mBinding.root)
        // 获取自定义属性
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ChatStyleWidget)
        val titleText = typedArray.getString(R.styleable.ChatStyleWidget_StyleTitleText)
        typedArray.recycle()

        // 应用属性值到 title 文本
        mBinding.tvTitle.text = titleText
        mBinding.sp1.isSelected = true
        mBinding.sp1.clickable {
            updateSelect(0)
        }
        mBinding.sp2.clickable {
            updateSelect(1)
        }
        mBinding.sp3.clickable {
            updateSelect(2)
        }
        mBinding.sp4.clickable {
            updateSelect(3)
        }
        mBinding.sp5.clickable {
            updateSelect(4)
        }
        mBinding.sp6.clickable {
            updateSelect(5)
        }
        mBinding.sp7.clickable {
            updateSelect(6)
        }
    }

    fun setOnStyleClickListener(listener: OnStyleClickListener) {
        this.listener = listener
    }
    fun setColor(color: Int) {
        val dcIndex = list.map { it.toColorInt() }
            .indexOf(color).coerceAtLeast(0)
        updateSelect(dcIndex, false)
    }

    fun getColor(): String {
        return list.get(currentSelect)
    }

    fun updateSelect(index: Int, needCallBack: Boolean = true) {
        currentSelect = index
        mBinding.sp1.isSelected = index == 0
        mBinding.sp2.isSelected = index == 1
        mBinding.sp3.isSelected = index == 2
        mBinding.sp4.isSelected = index == 3
        mBinding.sp5.isSelected = index == 4
        mBinding.sp6.isSelected = index == 5
        mBinding.sp7.isSelected = index == 6
        if(needCallBack) {
            listener?.onStyleClick(index, list[index])
        }
    }

    interface OnStyleClickListener {
        fun onStyleClick(index: Int, color: String)
    }


}